<template>
  <el-dialog v-model="dialogVisible" title="工单详情" width="60%" @close="handleClose">
    <div class="mt-4">
      <!-- 基本信息 -->
      <div class="mb-6">
        <div class="text-lg font-medium text-gray-700 mb-4">基本信息</div>

        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <label class="detail-label">接收人:</label>
              <span class="detail-value">{{ assigneerName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <label class="detail-label">接收时间:</label>
              <span class="detail-value">{{ formatTime(formData.taskReceive_time) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <label class="detail-label">任务开始时间:</label>
              <span class="detail-value">{{ formatTime(formData.jobStartTime) }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <label class="detail-label">实际开始时间:</label>
              <span class="detail-value">{{ formatTime(formData.taskStartTime) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <label class="detail-label">实际结束时间:</label>
              <span class="detail-value">{{ formatTime(formData.taskEndTime) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <label class="detail-label">实际工时(分):</label>
              <span class="detail-value">{{ formData.taskExecutionDuration }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <div class="detail-item">
              <label class="detail-label">保养人:</label>
              <span class="detail-value">{{ maintainerNames }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <div class="detail-item">
              <label class="detail-label">备注:</label>
              <span class="detail-value">{{ formData.description || '无' }}</span>
            </div>
          </el-col>
        </el-row>

        <div class="detail-item">
          <label class="detail-label">工单状态:</label>
          <span class="detail-value">{{ formData.isCompleted ? '已完成' : '未完成' }}</span>
        </div>
      </div>

      <!-- 保养项列表 -->
      <el-card class="box-card mt-20" shadow="never">
        <template #header>
          <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
            <span>保养项目列表</span>
            <div style="display: flex; align-items: center;">
              <span class="completed-count">已完成 {{ completedItemsCount }} / {{ upkeepItems.length }} 项</span>
            </div>
          </div>
        </template>

        <el-table :data="upkeepItems" class="items-table" border
          :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="保养项目名称" prop="itemName" min-width="150" />
          <el-table-column label="保养项目编码" prop="itemCode" width="120" />
          <el-table-column label="描述" min-width="200">
            <template #default="scope">
              <div class="rich-text-content" v-html="scope.row.itemDescription || '-'"></div>
            </template>
          </el-table-column>
          <el-table-column label="是否完成" width="100" align="center">
            <template #default="scope">
              <el-checkbox v-model="scope.row.isCompleted" disabled />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import { UpkeepTaskApi } from '@/api/mold/upkeeptask'
import { UpkeepItemApi } from '@/api/mold/upkeepitem'
import { dayjs } from 'element-plus'

interface UpkeepItem {
  id: number
  itemId: number
  itemName: string
  itemCode: string
  itemDescription: string
  isCompleted: boolean
}

interface FormDataType {
  id: number
  assigneerId: string
  taskReceive_time: string
  jobStartTime: string
  taskStartTime: string
  taskEndTime: string
  taskExecutionDuration: number
  assigneerIds: number[]
  description: string
  isCompleted: boolean
}

// 定义组件的 emits
const emit = defineEmits<{
  (e: 'close'): void
}>()

// 表单数据
const formData = reactive<FormDataType>({
  id: 0,
  assigneerId: '',
  taskReceive_time: '',
  jobStartTime: '',
  taskStartTime: '',
  taskEndTime: '',
  taskExecutionDuration: 0,
  assigneerIds: [],
  description: '',
  isCompleted: false
})

// 接收人名称
const assigneerName = ref('')

// 保养人名称列表
const maintainerNames = ref('')

// 保养项列表
const upkeepItems = ref<UpkeepItem[]>([])

// 保养人员列表
const maintainerList = ref<UserVO[]>([])

// 对话框状态
const dialogVisible = ref(false)

// 计算已完成的保养项数量
const completedItemsCount = computed(() => {
  return upkeepItems.value.filter(item => item.isCompleted).length
})

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetData()
  emit('close')
}

// 重置数据
const resetData = () => {
  formData.id = 0
  formData.assigneerId = ''
  formData.taskReceive_time = ''
  formData.jobStartTime = ''
  formData.taskStartTime = ''
  formData.taskEndTime = ''
  formData.taskExecutionDuration = 0
  formData.assigneerIds = []
  formData.description = ''
  formData.isCompleted = false
  assigneerName.value = ''
  maintainerNames.value = ''
  upkeepItems.value = []
}

// 格式化时间显示
const formatTime = (timestamp: string) => {
  if (!timestamp) return '-'
  // 如果是字符串或数字形式的时间戳，转换为数字
  const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
  return dayjs(ts).format('YYYY-MM-DD HH:mm:ss')
}

// 获取保养人员列表
const getMaintainerList = async () => {
  try {
    maintainerList.value = await UserApi.getSimpleUserList()
  } catch (error) {
    console.error('获取保养人员列表失败', error)
  }
}

// 获取保养项列表
const getUpkeepItems = async (taskId: number) => {
  try {
    const data = await UpkeepItemApi.getItemsOfTask(taskId)
    // 转换isCompleted为布尔值
    upkeepItems.value = data.map(item => ({
      ...item,
      isCompleted: !!item.isCompleted
    }))
  } catch (error) {
    console.error('获取保养项列表失败', error)
  }
}

// 获取保养人名称
const getMaintainerNames = (ids: number[]) => {
  if (!ids.length) return '无'
  return ids.map(id => {
    const user = maintainerList.value.find(user => user.id === id)
    return user ? user.nickname : `未知用户(${id})`
  }).join('，')
}

// 打开弹窗方法
const open = async (id: number) => {
  try {
    resetData()

    // 调用接口查询需要的数据
    const result = await UpkeepTaskApi.getUpkeepTask(id)

    // 填充表单数据
    formData.id = result.id
    formData.assigneerId = result.assigneerId ? result.assigneerId.toString() : ''
    formData.taskReceive_time = result.taskReceiveTime || ''
    formData.jobStartTime = result.jobStartTime || ''
    formData.taskStartTime = result.taskStartTime || ''
    formData.taskEndTime = result.taskEndTime || ''
    formData.taskExecutionDuration = result.taskExecutionDuration || 0
    formData.assigneerIds = result.assigneerIds || []
    formData.description = result.description || ''
    formData.isCompleted = result.isCompleted || false

    // 设置接收人名称
    const assigneer = maintainerList.value.find(user => user.id === result.assigneerId)
    assigneerName.value = assigneer ? assigneer.nickname : '未知用户'

    // 设置保养人名称
    maintainerNames.value = getMaintainerNames(formData.assigneerIds)

    // 获取保养项列表
    await getUpkeepItems(result.id)

    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取任务详情失败')
    console.error('获取任务详情失败:', error)
  }
}

// 初始化获取保养人员列表
getMaintainerList()

// 暴露方法给父组件
defineExpose({
  open
})
</script>

<style scoped>
.detail-item {
  margin-bottom: 16px;
}

.detail-label {
  display: block;
  font-weight: 500;
  color: #606266;
  margin-bottom: 4px;
}

.detail-value {
  color: #303133;
  word-break: break-all;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.mb-6 {
  margin-bottom: 24px;
}

.text-lg {
  font-size: 16px;
}

.font-medium {
  font-weight: 500;
}

.text-gray-700 {
  color: #4a4a4a;
}

.mt-20 {
  margin-top: 20px;
}

.rich-text-content {
  line-height: 1.6;
}

.items-table {
  width: 100%;
  margin-top: 15px;
}

.completed-count {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>